package assets
{
	import away3d.arcane;
	use namespace arcane; 
	
	import events.LoadedEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.System;
	
	import tool.DataParser;
	
	/**
	 * 3D骨骼动画的管理器，通常是在AssetMesh取出skinnedMesh类模型时自动使用的，一般不单独使用这个管理器
	 */	
	public class AssetSkeleton extends EventDispatcher
	{
		///////////////////////////////////////////////
		private var loadingList:Array = new Array;
		private var currentLoadingURL:String;
		private var loader:URLLoader;
		
		///////////////////////////////////////////////
		public function AssetSkeleton()
		{
			loader = new URLLoader;
			loader.addEventListener(IOErrorEvent.IO_ERROR,onError);
		}
		
		public function load(URL:String):void
		{
			//trace("loadASK:",URL);
			
			if(loadingList.indexOf(URL) > -1)return;
			
			if(Asset.resSkeletons[URL] == undefined)
			{
				loadingList.push(URL);
				
				if(loadingList.length==1)loadNext();
			}else{
				dispatchEvent(new LoadedEvent(URL,LoadedEvent.SKELETON_COMPLETE));
			}
		}
		
		///////////////////////////////////////////////
		
		private function onError(e:IOErrorEvent):void
		{
			var errorInfo:String ="没有此资源："+ currentLoadingURL;
			throw new Error(errorInfo);
		}
		
		private function loadNext():void
		{
			currentLoadingURL = loadingList[0];
			loader.addEventListener(Event.COMPLETE,onLoadComplete);
			loader.load(new URLRequest(currentLoadingURL));
		}
		
		private function onLoadComplete(e:Event):void
		{
			var _xml:XML = new XML(loader.data);
			
			Asset.resSkeletons[currentLoadingURL] = DataParser.getAnimateSkeleton(_xml);
			
			System.disposeXML(_xml);
			loader.close();
			
			loadingList.splice(0,1);
			dispatchEvent(new LoadedEvent(currentLoadingURL,LoadedEvent.SKELETON_COMPLETE));
			
			//------------
			if(loadingList.length == 0)
			{
				loader.removeEventListener(Event.COMPLETE,onLoadComplete);
				return;
			}
			
			loadNext();
		}
		
		
	}
}